package com.kurumi.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import ca.uhn.hl7v2.AcknowledgmentCode;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v25.message.ACK;
import ca.uhn.hl7v2.parser.PipeParser;
import ca.uhn.hl7v2.util.Terser;

public class SocketServer extends Thread{
	
	private static final int BUFFER_SIZE=1024*1024; 
	private static  final String CHARSET = "UTF-8"; 
	
	
	private ServerSocket serverSocket;
	
	public SocketServer(int port) throws IOException{
		//创建指定端口ServerSocket
		serverSocket = new ServerSocket(port);
		//设置ServerSocket的超时时间(单位:毫秒)
		serverSocket.setSoTimeout(0);
	}
	public void run(){
		System.err.println("监听客户端");
		Socket server = null;
		while(true){
			try{ 
				//监听客户端Socket并获取客户端Socket对象
				server = serverSocket.accept(); 
				
				//接受Socket信息
	            BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream(), CHARSET)); 
	            
	            StringBuilder sb = new StringBuilder();
	            String dataStr = null;
	            while((dataStr = br.readLine()) !=null){
	            	sb.append(dataStr+"\r");
	            }
	            PipeParser pipeParser = new PipeParser();
	    	    Message message;
	    	    ACK ack = null;
	    		try {
	    			
	    			message = pipeParser.parse(sb.toString());
	    			Terser terser = new Terser(message);
	    			String sendingAppCode = terser.get("/MSH-3-1");
	    			String receivingAppCode = terser.get("/MSH-5-1");
	    			String messageTypeCode =terser.get("/MSH-9-1");
	    			String triggerEventCode = terser.get("/MSH-9-2");
	    			String hapiVersion = terser.get("/MSH-12");
	    			String sendMessageControlID = terser.get("/MSH-10");
	    			if(triggerEventCode.equalsIgnoreCase("A01")){
	    				
		    			String mrId = terser.get("/PID-3(3)-1");
		    			System.out.println("病案号:"+mrId);
		    			String patientName = terser.get("/PID-5");
		    			System.out.println("患者姓名:"+patientName);
		    			String idNumber = terser.get("/PID-19");
		    			System.out.println("身份证:"+idNumber);
		    			String sexCode = terser.get("/PID-8");
		    			System.out.println("性别:"+sexCode);
		    			String sexName = null;
		    			if(sexCode != null){
		    				if("F".equalsIgnoreCase(sexCode)){
		    					sexName = "女性";
		    				}else if("M".equalsIgnoreCase(sexCode)){
		    					sexName = "男性";
		    				}else if("U".equalsIgnoreCase(sexCode)){
		    					sexName = "未知";
		    				}
		    			}
		    			System.out.println("性别:"+sexName);
		    			String marriageCode = terser.get("/PID-16-1");
		    			System.out.println("婚姻:"+marriageCode);
		    			String marriageName = terser.get("/PID-16-2");
		    			System.out.println("婚姻:"+marriageName);
		    			String nationalityCode = terser.get("/PID-22-1");
		    			System.out.println("民族:"+nationalityCode);
		    			String nationalityName = terser.get("/PID-22-2");
		    			System.out.println("民族:"+nationalityName);
		    			String nationCode = terser.get("/PID-28-1");
		    			System.out.println("国籍:"+nationCode);
		    			String nationName = terser.get("/PID-28-2");
		    			System.out.println("国籍:"+nationName);
		    			String bloodTypeCode = terser.get("/PID-35");
		    			System.out.println("血型:"+bloodTypeCode);
		    			String visitNumber = terser.get("/PV1-1");
		    			System.out.println("住院次数:"+visitNumber);
		    			String inHospitalDateTime = terser.get("/PV1-44");
		    			System.out.println("入院时间:"+inHospitalDateTime);
		    			String inDeptCode = terser.get("/PV1-3-4-1");
		    			System.out.println("入院科室代码:"+inDeptCode);
		    			
		    			String inDeptName = terser.get("/PV1-3-4-2");
		    			System.out.println("入院科室名称:"+inDeptName);
		    			ack = HL7Util.getACK(receivingAppCode, sendingAppCode, messageTypeCode, triggerEventCode, hapiVersion, AcknowledgmentCode.AA, sendMessageControlID,null);
		    			
	    			}else if(triggerEventCode.equalsIgnoreCase("A03")){
	    				ack = HL7Util.getACK(receivingAppCode, sendingAppCode, messageTypeCode, triggerEventCode, hapiVersion, AcknowledgmentCode.AA, sendMessageControlID,null);
		    			
	    			}else if(triggerEventCode.equalsIgnoreCase("A08")){
	    				ack = HL7Util.getACK(receivingAppCode, sendingAppCode, messageTypeCode, triggerEventCode, hapiVersion, AcknowledgmentCode.AA, sendMessageControlID,null);
		    			
	    			}else{
	    				String textMessage = "不需要处理此类消息";
	    				ack = HL7Util.getACK(receivingAppCode, sendingAppCode, messageTypeCode, triggerEventCode, hapiVersion, AcknowledgmentCode.AR, sendMessageControlID,textMessage);
		    			
	    			}
	    			
	    			
	    		} catch (HL7Exception e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}catch (Exception e) {
					// TODO: handle exception
	    			e.printStackTrace();
				}
				/*System.out.println(sb.toString());*/
				//发送Socket信息
	    		OutputStreamWriter osw = new OutputStreamWriter(
	    				server.getOutputStream(), "UTF-8");
	    		PrintWriter pw= new PrintWriter(osw, true);
	    		if(ack != null){
	    			try {
						pw.print(new PipeParser().encode(ack));
					} catch (HL7Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    		}else{
	    			pw.print("Thank you for connecting to "+ server.getLocalSocketAddress());
	    		}
	    		
	    		pw.flush();
	    		server.shutdownOutput();
			}
			catch(SocketTimeoutException s){
				System.out.println("Socket timed out!");
			}catch(IOException e){
				e.printStackTrace();
			}/*finally{
				if(server != null){
					try {
						server.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}*/
		}
	}
}
